import { Http, HttpRequestConfig, HttpRequestOptions } from './http'

type Interceptors<OriginResult,NewResult> = {
    onRequest?: (config: HttpRequestConfig) => HttpRequestConfig | PromiseLike<HttpRequestConfig>
    onResult: (result: OriginResult) => NewResult | PromiseLike<NewResult>
    onError?: (error: Error) => NewResult | PromiseLike<NewResult>
}

export class InterceptorHttp<OriginResult, NewResult> extends Http<NewResult> {

    constructor(private http: Http<OriginResult>,
        public interceptors: Interceptors<OriginResult,NewResult>) {
        super()
    }

    request(url: string, options: HttpRequestOptions): Promise<NewResult> {
        return Promise.resolve({ url, options })
            .then(this.interceptors.onRequest)
            .then(config => this.http.request(config.url, config.options))
            .then((!options.responseType || options.responseType === 'json') ? this.interceptors.onResult : undefined)
            .catch(this.interceptors.onError)
    }
}
